<?php
/**
 * UploadModel
 * Model for do upload
 * @author Tuan Ngo
 * @version 1.0
 */
class UploadModel
{
	/**
	 * upload
	 * Upload a file to specified path
	 * @param string $name name of file input
	 * @param string $upload_path the path for upload file to
	 */
    public function upload ($name, $upload_path, $base_url = "")
    {
        if ($_FILES[$name]['name']) {
			$path_file = $upload_path . $this->getRandVersion() .$_FILES[$name]["name"];
			move_uploaded_file($_FILES[$name]["tmp_name"], $path_file);
			
			return $base_url . "/" .$path_file;
        }
    }
    
    /**
     * Upload a image, resize if it needed
     * Return a link
     * @param $name
     * @param $upload_path
     * @param $base_url
     * @param $max_size
     */
	public function uploadImage ($name, $upload_path, $base_url = "", $max_size = NULL)
    {
    	Zend_Loader::loadClass("ImageModel");
    	
        if ($_FILES[$name]['name']) {            
        	$file_name = $this->getRandVersion() .$_FILES[$name]["name"];
			$path_file = $upload_path . $file_name;
			
			if(!$max_size){//if not need to resize
				move_uploaded_file($_FILES[$name]["tmp_name"], $path_file);
				return $base_url . $path_file;
			}else{
				//need to resize
				move_uploaded_file($_FILES[$name]["tmp_name"], $path_file);
				$image = new ImageModel();
				$image->setFile($path_file);
            	$image->setUploadDir($upload_path);
            	if(($image->img_w)>$max_size || ($image->img_h>$max_size)){
            		$image->resize($max_size);
           	 	}
           	 	
            	$image->createFile($file_name);
            	return $base_url . "/" .$path_file;
			}
        }
    }
    
    
    
    /**
     * getRandVersion
     * Get randdom number to versionize a file on server
     */
    public function getRandVersion(){
    	return rand(1, 100000);
    }
}
?>